<template>
    <div class="issueOrder">
        <div class="main">
            <div class="content">
                <van-cell-group>
                    <van-field
                            v-model.trim="orderInfo.orderContent"
                            rows="4"
                            type="textarea"
                            maxlength="80"
                            show-word-limit
                            :placeholder="$t('orders.fieldPlaceholder')"
                    ></van-field>
                </van-cell-group>
            </div>
            <div class="uploadOrderImage">
                <div class="tips">{{ $t("orders.maxSupportUploadImage") }}</div>
                <van-uploader
                        v-model="orderInfo.orderPicture"
                        multiple
                        :max-count="3"
                        :after-read="afterRead"
                ></van-uploader>
            </div>
            <div class="ordersupplementInfo">
                <van-cell-group>
                    <van-cell
                            :title="$t('orders.reward')"
                            class="goldPrice"
                            icon="gold-coin"
                            :value="orderInfo.orderPrice && orderInfo.orderPrice + this.$t('dollar')"
                            clickable
                            is-link
                            arrow-direction="down"
                            @click="disOverlay('showPriceBox')"
                    ></van-cell>
                    <van-cell
                            :title="$t('orders.arriveTime')"
                            icon="underway"
                            is-link
                            @click="chooseDate"
                            arrow-direction="down"
                    >
                        <template #default>
                            <div>{{orderInfo.completionTime}}</div>
                            <div>{{orderInfo.timeFrame}}</div>
                        </template>
                    </van-cell>
                    <van-cell
                            :title="$t('filters.expressBrand')"
                            icon="bookmark"
                            :value="orderInfo.orderType"
                            is-link
                            arrow-direction="down"
                            class="expressBrand"
                            @click="disOverlay('showExpressBox')"
                    ></van-cell>
                    <van-cell
                            :title="$t('orders.destination')"
                            icon="map-marked"
                            is-link
                            class="chooseAddress"
                            @click="toAddressRoute"
                    >
                        <div slot="default">
                            <div class="slotTop">
                                <span class="name">{{ orderInfo.orderAuthor }}</span>
                                <span class="phone">{{ orderInfo.orderPhone }}</span>
                            </div>
                            <div class="slotBottom">{{ orderInfo.orderAddress }}</div>
                        </div>
                    </van-cell>
                </van-cell-group>
            </div>
            <div class="nextStep">
                <slot name="button"></slot>
            </div>
            <van-popup
                    v-model="showLayer"
                    position="bottom"
                    :style="{ height: '50%' }"
            >
                <van-tree-select
                        @click-item="itemChange"
                        :items="items"
                        height="100%"
                        :active-id.sync="activeId"
                        :main-active-index.sync="activeIndex"
                />
            </van-popup>
            <van-overlay :show="showOverlay" @click="closedOverlay">
                <div class="wrapper">
                    <div class="selected" v-if="showPriceBox">
                        <van-radio-group v-model="orderInfo.orderPrice">
                            <van-radio
                                    :name="item"
                                    icon-size="24px"
                                    v-for="(item, index) in defaultPrice"
                                    :key="index"
                            >{{ item + $t("dollar") }}</van-radio>
                        </van-radio-group>
                    </div>
                    <div class="express" v-if="showExpressBox">
                        <van-radio-group
                                v-model="orderInfo.orderType"
                        >
                            <van-radio
                                    icon-size="24px"
                                    v-for="(item, index) in expressBrand"
                                    :name="item"
                                    :key="index"
                            >{{ item }}</van-radio
                            >
                        </van-radio-group>
                    </div>
                </div>
            </van-overlay>
        </div>
        <slot name="submit" :orderInformation="orderInfo"></slot>
    </div>
</template>

<script>
import { Field, CellGroup, Overlay, Cell, Uploader, Popup, Button, RadioGroup, Radio, TreeSelect } from 'vant';
import 'vant/lib/field/style/less';
import 'vant/lib/uploader/style/less';
import 'vant/lib/stepper/style/less';
import 'vant/lib/tree-select/style/less';
import 'vant/lib/radio-group/style/less';
import 'vant/lib/radio/style/less';
import expressBrand from '@/config/data/express-brand.json';

export default {
    name: 'issue-component',
    props: {
        orderInformation: {
            type: Object
        }
    },
    components: {
        [CellGroup.name]: CellGroup,
        [Cell.name]: Cell,
        [Field.name]: Field,
        [Uploader.name]: Uploader,
        [Overlay.name]: Overlay,
        [Popup.name]: Popup,
        [Button.name]: Button,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio,
        [TreeSelect.name]: TreeSelect
    },
    data () {
        return {
            expressBrand,
            items: [], // 送达时间列表
            beforeItemIndex: 0, // 之前的父级
            lastParentIndex: 0, // 之前的父级下的位置
            lastIndex: -1,
            activeId: -1, // 默认不选中选中下标
            activeIndex: 0, // 索引
            defaultPrice: [5, 10, 15, 20, 25, 30], // 默认订单价格
            showLayer: false, // 是否展示弹出层
            showPriceBox: false, // 是否展示酬金内容
            showExpressBox: false,
            showOverlay: false, // 是否展示遮罩层
            orderInfo: null // 订单信息
        };
    },
    created () {
        if (JSON.stringify(this.$store.state.tempIssueOrderInfo) !== '{}') {
            const data = this.$store.state.tempIssueOrderInfo;
            this.orderInfo = Object.assign({}, this.orderInfo, data);
            this.$store.commit('simpleAssignment', {
                state: 'tempIssueOrderInfo',
                value: {}
            });
        } else {
            this.orderInfo = this.orderInformation || {
                orderByCreateID: localStorage.getItem('id'),
                orderPrice: '',
                orderType: '',
                orderContent: '',
                completionTime: '',
                orderAuthor: '',
                orderPhone: '',
                orderAddress: '',
                timeFrame: '',
                orderPicture: []
            };
        }
        this.items = this.getTreeSelectItems;
    },
    methods: {
        chooseDate () {
            this.showLayer = true;
        },
        // 显示全局遮罩层
        disOverlay (propertyName) {
            this.showOverlay = true;
            this[propertyName] = true;
        },
        // 关闭全局遮罩层
        closedOverlay () {
            setTimeout(() => {
                this.showOverlay = false;
                this.showExpressBox = false;
                this.showPriceBox = false;
            }, 200);
        },
        toAddressRoute () {
            this.$store.commit('overRideValue', {
                state: 'tempIssueOrderInfo',
                value: this.orderInfo
            });
            this.$router.push({ name: 'my-address' });
        },
        afterRead (value) {
            // TODO 校验文件大小
        },
        // 转换成当天的毫秒数
        toSeconds (...args) {
            return args[0][0] * 60 * 60 + args[0][1] * 60 + args[0][2] * 1;
        },
        // 是否禁用列表项
        isDisableClick (setHours, currentHours) {
            const start = setHours.split('-')[0].trim().split(':')[0];
            const end = setHours.split('-')[1].trim().split(':')[0];
            return currentHours >= start * 60 * 60 && currentHours >= end * 60 * 60;
        },
        // 生成列表树
        makeTreeItem (totalSeconds) {
            const treeItem = [];
            for (let index = 0; index < 2; index++) {
                treeItem.push({
                    text: index ? this.$t('tomorrow') : this.$t('today'),
                    children: []
                });
                const timeStart = 8;
                for (let subIndex = 0; subIndex < 7; subIndex++) {
                    const text = `${!subIndex ? '0' + timeStart : timeStart + subIndex * 2}:00-${timeStart +
                        (subIndex + 1) * 2}:00`;
                    treeItem[index].children.push({
                        id: subIndex,
                        text,
                        disabled: index === 0 ? this.isDisableClick(text, totalSeconds) : false
                    });
                }
            }
            return treeItem;
        },
        itemChange (value) {
            this.lastParentIndex = this.activeIndex;
            this.showLayer = false;
            const tomorrow = this.$moment().add(1, 'days')._d;
            const tomorrowDate = new Date(tomorrow).toLocaleDateString();
            this.orderInfo.completionTime = !this.activeIndex ? new Date().toLocaleDateString() : tomorrowDate;
            this.orderInfo.timeFrame = value.text;
        }
    },
    computed: {
        // 获取跑腿时间列表
        getTreeSelectItems () {
            const currentTime = new Date().toLocaleTimeString('chinese', { hour12: false });
            const totalSeconds = this.toSeconds(currentTime.split(':')); // 总秒数
            return this.makeTreeItem(totalSeconds * 1);
        }
    },
    watch: {
        activeIndex: {
            handler (after) {
                if (this.lastParentIndex === after) {
                    this.activeId = this.lastIndex;
                } else {
                    this.lastIndex = this.activeId;
                    this.activeId = -1;
                }
            }
        }
    }
};
</script>

<style scoped lang="less" src="./less/issue-order.less"></style>
